package lgkj.meicqt20.utils;

import android.app.Activity;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.orhanobut.logger.Logger;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import lgkj.meicqt20.utils.tilepuzzle.ClassBoardModel;
import okhttp3.Call;

/**
 * Created by Administrator on 2018/6/28 0028.
 */

public class HttpUtils {

    private static String TAG = "HttpUtils";
    private static String erweimaLoadPath = "";
    public static String ver = "1.0";  //新终端
    private static boolean iserweima = false;   //上来加载一次
    public static String user = "";
    public static String tel = "";
    public static String httpHederKey = "Referer";
    public static String httpHederValue = "http://md.05948166.com";
    private static String erweiUrl = "";

    private static String urlName(String url) {
        return "." + url.substring(url.lastIndexOf("/") + 1, url.length());
    }

    /**
     * get请求
     *
     * @param params
     * @param url
     * @param httpCallBack
     */
    public static void getHttp(Map<String, String> params, final String url, final HttpCallBack httpCallBack) {
        if (url == null || url.length() == 0) {
            Logger.d(TAG + urlName(url) + "get:url不能为空");
            return;
        }
        if (params == null) {
            params = new HashMap<>();
        }
        String mac = CommUtils.getLocalMacAddressFromWifiInfo(ClassBoardModel.getContext());
        params.put("mac", mac);
        params.put("ver", ver);
        params.put("tel", tel);
        params.put("user", user);
        String strParam = params.toString().replaceAll(" ", "");
        Log.w(TAG + urlName(url), url + "?" + strParam.replaceAll(",", "&").substring(1, strParam.length() - 1));
        OkHttpUtils.get().params(params).url(url).build().connTimeOut(5000).writeTimeOut(5000).readTimeOut(5000).execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG + urlName(url), "onError" + e.getMessage());
                httpCallBack.errorHttp(e.getMessage());
            }


            @Override
            public void onResponse(String response, int id) {
                JSONObject object = null;
                try {
                    Logger.json(response);
                    object = new JSONObject(response);
                    httpCallBack.successHttp(object, id);
                } catch (JSONException e) {
                    Logger.e(TAG + urlName(url), "onError:" + e.getMessage());
                }

            }
        });
    }


    /**
     * @param url          下载地址
     * @param fileCallBack
     */
    public static void getFile(String url, final FileCallBack fileCallBack) {
        try {
            Log.d(TAG + urlName(url), "文件下载路径:" + url);
            OkHttpUtils.get().url(url).build().execute(fileCallBack);
        } catch (Exception e) {
            Log.e(TAG + urlName(url), "下载地址路有误！url:" + url);
            Log.e(TAG + urlName(url), e.getMessage());
        }
    }

    /**
     * http 请求回调
     */
    public interface HttpCallBack {
        void successHttp(JSONObject jsonObject, int id);

        void errorHttp(String msg);
    }


    /**
     * 获取在线二维码
     *
     * @param act
     * @param imageView
     */
    public static void getQRCode(final Activity act, final ImageView imageView) {
        if (act.isDestroyed()) {
            return;
        }
        final File file = new File(AllKindsOfConstant.NEW_VERSION_PATH + erweimaLoadPath);
//        Glide.with(act).load("http://md.05948166.com/meidian/Public/qr/15317117889894.png").override(140, 140).into(imageView);
        if (file.exists() && file.length() > 0 && iserweima) {
            Log.i(TAG, "getQRCode: " + file.exists() + "," + file.isFile() + "," + iserweima + ",lenth:" + file.length());
            Log.i(TAG, "getQRCode: " + AllKindsOfConstant.NEW_VERSION_PATH + erweimaLoadPath);
            Glide.with(act).load(file).into(imageView);
//            Glide.with(act).load("http://md.05948166.com/meidian/Public/qr/15317117889894.png").override(140, 140).into(imageView);
        } else {
            getHttp(null, AllKindsOfConstant.GET_QR_CODE, new HttpCallBack() {
                @Override
                public void successHttp(JSONObject jsonObject, int id) {
                    if (jsonObject.optInt("status") == 1) {
                        String erweimaUrl = jsonObject.optString("data");
                        erweiUrl = erweimaUrl;
                        erweimaLoadPath = VideoDownLoadUtil.getVideoFullName(erweimaUrl);
                        getPuzzleImge(erweimaUrl, erweimaLoadPath);
                        iserweima = true;
                    }
                }

                @Override
                public void errorHttp(String msg) {
                    Glide.with(act).load(AllKindsOfConstant.NEW_VERSION_PATH + erweimaLoadPath).override(140, 140).into(imageView);
                }
            });
        }

    }


    /**
     * 下载拼图
     *
     * @param params
     */
    public static void getPuzzle(Map<String, String> params) {
        getHttp(params, AllKindsOfConstant.getgame, new HttpCallBack() {
            @Override
            public void successHttp(JSONObject jsonObject, int id) {
                try {
                    if (jsonObject.getInt("status") == 1) {
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        AllKindsOfConstant.puzzleName = new String[jsonArray.length()];
                        for (int i = 0; i < jsonArray.length(); i++) {
                            String url = jsonArray.getJSONObject(i).getString("puzzle_url");
                            Log.d(TAG, "successHttp: " + url);
                            AllKindsOfConstant.puzzleName[i] = VideoDownLoadUtil.getVideoFullName(url);
                            getPuzzleImge(url, AllKindsOfConstant.puzzleName[i]);
                        }
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "successHttp: " + e.getMessage());
                }
            }

            @Override
            public void errorHttp(String msg) {
            }
        });
    }

    /**
     * 下载拼图  联广
     *
     * @param url
     */
    private static void getPuzzleImge(String url, String name) {
        getFile(url, new FileCallBack(AllKindsOfConstant.NEW_VERSION_PATH, name) {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.d(TAG, "onError: 拼图下载失败" + e.getMessage());
            }

            @Override
            public void onResponse(File response, int id) {
                Log.d(TAG, "onResponse: 拼图下载成功");
            }
        });
    }

}
